<template>
  <base-breadcrumb
    :title="$route.meta.title"
    :breadcrumb="!isAudit"
  >
    <!-- 组织架构编辑 -->
    <a-spin :spinning="loading.SUBMITTED || loading.DRAFT || loading.REJECTED || editParsion">
      <a-form-model
        ref="ruleForm"
        :model="form"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
        :rules="editModel != 0 ? rules : {}"
      >
        <!-- 表单 -->
        <a-card :bordered="false">
          <title-name title="基本信息" />
          <custom-form
            ref="customForm"
            :form-list="formList"
            :form="form"
            :edit-model="editModel == 0 ? '' : ''"
            @changeDepId="changeDepId"
            @changeOrg="changeOrg"
            @onSelectChange="(naem, e) => (form.unionChairmanName = e.name)"
          >
            <!-- 人数 -->
            <template #unionVipNum>
              <BaseInput
                v-model="form.unionVipNum"
                disabled
              />
              <SelectOrgPeople
                v-show="false"
                :org-ids="form.orgIds"
                init
                :api="getUserDeptByOrgId"
                :is-array="true"
                @changePersonNumber="changePersonNumber"
              />
            </template>
            <!-- 状态 -->
            <template #auditStatus>
              <BaseInput
                v-model="form.auditStatusStr"
                disabled
              />
            </template>
          </custom-form>
          <!-- </a-form-model> -->
        </a-card>

        <a-card :bordered="false">
          <!-- 工会管理人员 -->
          <title-name title="工会管理人员" />
          <a-row :gutter="24">
            <a-col
              :md="24"
              :sm="24"
            >
              <div class="flex-row mb20">
                <a-button
                  :disabled="isDisabled()"
                  class="ml20"
                  type="primary"
                  @click="addLine()"
                >
                  添加行
                </a-button>
              </div>
              <s-table
                ref="table"
                bordered
                size="default"
                row-key="key"
                :columns="columns"
                :data="loadData"
                :is-delete="true"
                :alert="true"
                show-size-changer
                show-quick-jumper
                :show-pagination="false"
              >
                <template
                  slot="userId"
                  slot-scope="text, record"
                >
                  <SelectOrgPeople
                    v-model="record.userId"
                    :disabled="!record.editable"
                    :org-ids="form.orgIds"
                    style="max-width: 380px"
                    init
                    placeholder="请选择"
                    :api="getUserDeptByOrgId"
                    :is-array="true"
                    :custom-render="customRender"
                    @onSelectChange="record.phone = $event.phoneNum"
                  />
                </template>
                <template
                  slot="postId"
                  slot-scope="text, record"
                >
                  <Selector
                    v-model="record.postId"
                    :disabled="!record.editable"
                    url-type="union"
                    :select-type="
                      form.unionLevelId == '605004340528287745'
                        ? '2'
                        : form.unionLevelId == '605004401341501446'
                          ? '3'
                          : '4'
                    "
                    placeholder="请选择"
                  />
                </template>
                <template
                  slot="joinDate"
                  slot-scope="text, record"
                >
                  <a-date-picker
                    v-model="record.joinDate"
                    :disabled="!record.editable"
                    placeholder="请选择"
                    value-format="YYYY-MM-DD"
                  />
                </template>
                <template
                  slot="phone"
                  slot-scope="text, record"
                >
                  <span>{{ record.phone }}</span>
                </template>
                <template
                  slot="action"
                  slot-scope="text, record, index"
                >
                  <span v-if="record.editable">
                    <a @click="() => save(record)">保存</a>
                    <a-divider type="vertical" />
                    <a-popconfirm
                      title="确定要取消保存?"
                      @confirm="() => cancel(record.key, index)"
                    >
                      <a>取消</a>
                    </a-popconfirm>
                  </span>
                  <span v-else>
                    <a
                      :disabled="editingKey !== '' || isDisabled()"
                      @click="() => edit(record.key)"
                    >编辑</a>
                    <a-divider type="vertical" />
                    <a-popconfirm
                      title="确定要删除?"
                      @confirm="() => del(record, index)"
                    >
                      <a :disabled="editingKey !== '' || isDisabled()">删除</a>
                    </a-popconfirm>
                  </span>
                </template>
              </s-table>
            </a-col>
          </a-row>
        </a-card>
      </a-form-model>
    </a-spin>
    <!-- 页脚操作栏 -->
    <div
      v-if="editModel != 0"
      class="tool-btns page-btn-right-top"
    >
      <a-button
        v-if="form.auditStatus == 'REJECTED'"
        :loading="loading.REJECTED"
        :disabled="loading.SUBMITTED || loading.DRAFT"
        type="primary"
        class="button_right"
        @click="handleSubmit(form.auditStatus)"
      >
        保存
      </a-button>
      <a-button
        v-else
        :loading="loading.DRAFT"
        :disabled="loading.SUBMITTED || loading.REJECTED"
        type="primary"
        class="button_right"
        @click="handleSubmit('DRAFT')"
      >
        保存草稿
      </a-button>

      <a-button
        :loading="loading.SUBMITTED"
        :disabled="loading.REJECTED || loading.DRAFT"
        type="primary"
        class="button_right ml20"
        @click="handleSubmit('SUBMITTED')"
      >
        提交
      </a-button>
      <a-button
        class="ml20"
        type="primary"
        @click="handleClose"
      >
        关闭
      </a-button>
    </div>
    <div
      v-else
      class="tool-btns page-btn-right-top"
    >
      <a-button
        v-if="addpersion == 'true'"
        :loading="editParsion"
        type="primary"
        class="button_right"
        @click="handleSubmit(form.auditStatus)"
      >
        保存
      </a-button>
      <a-button
        class="ml20"
        type="primary"
        @click="handleClose"
      >
        关闭
      </a-button>
    </div>
    <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>

<script>
import {
    getOrganization,
    addOrganization,
    updateOrganization,
    getUserDeptByOrgId,
} from '@/api/union/organizationManagement' // api

import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import TreeSelectOrganization from '@/components/TreeSelectOrganization'
import { STable } from '@/components' // 表格
import SelectUnionOrg from '@/components/Select/SelectUnionOrg'
import SelectUnit from '@/components/Select/SelectUnit'

import SelectOrgPeople from '@/components/Select/SelectOrgPeople'
import Selector from '@/components/Select/Selector'
const columns = [
    {
        title: '序号',
        dataIndex: 'index',
        customRender() {
            return arguments[2] + 1
        },
    },
    {
        title: '姓名',
        dataIndex: 'userId',
        scopedSlots: { customRender: 'userId' },
        width: '30%',
    },
    {
        title: '工会职务',
        dataIndex: 'postId',
        scopedSlots: { customRender: 'postId' },
        width: '30%',
    },
    {
        title: '工会任职时间',
        dataIndex: 'joinDate',
        scopedSlots: { customRender: 'joinDate' },
        width: '15%',
    },
    {
        title: '电话号码',
        dataIndex: 'phone',
        scopedSlots: { customRender: 'phone' },
        width: '10%',
    },
    {
        title: '操作',
        dataIndex: 'action',
        scopedSlots: { customRender: 'action' },
    },
]
export default {
    name:'a'+Date.now(),
    extends: new BaseEditPage(),
    components: {
        SelectOrgPeople,
        Selector,
        STable,
    },
    data() {
        this.columns = columns
        return {
            customRender: (q) => {
                let result = q.name
                if (q.postPNames && q.postPNames.length) {
                    result = `${result} (${q.postPNames.join('/')}) `
                }
                return result
            },
            loading: { DRAFT: false, REJECTED: false, SUBMITTED: false }, // 草稿和提交按钮loding
            editParsion: false,
            editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
            form: {
                unionVipNum: 0,
                orgIds: [],
                unionOrgName: '',
                unionChairmanId: '',
                parentId: '',
                unionEmployees: [],
            },
            orgIds: [],
            rules: {
                unionLevelId: [{ required: true, whitespace: true, message: '请选择层级', trigger: 'change' }],
                parentId: [{ required: true, message: '请选择上级工会组织', trigger: 'change' }],
                orgIds: [{ required: true, message: '请选择单位', trigger: 'change' }],
                unionOrgName: [{ required: true, message: '请输入组织简称', trigger: 'change' }],
                unionEstDate: [{ required: true, message: '请选择成立日期', trigger: 'change' }],
                unionChairmanId: [{ required: true, message: '请选择工会主席 ', trigger: 'change' }],
                unionChairmainJoinDate: [{ required: true, message: '请选择任职日期 ', trigger: 'change' }],
                // remarks: [{ required: true, message: '请输入备注', trigger: 'change' }],
            }, // 校验规则
            init: false, // 初始化控件
            formCode: '', // 形式选中项code
            key: 0,
            cacheData: {},
            editingKey: '',
            getUserDeptByOrgId: getUserDeptByOrgId,
            addpersion: false,
            isAuth: 1,
            loadData: () => {
                return new Promise((resolve, reject) => {
                    resolve({
                        data: this.form.unionEmployees,
                    })
                })
            },
          //获取流程配置值
          processConfig: null,
          //点击提交发送流程配置值
          setProcessConfig: null,
          businessId: null
        }
    },
    props: {
        isAudit: {
            // 是否作为审批详情
            type: Boolean,
            default: false,
        },
    },
    watch: {
        'form.orgIds'() {
            // console.log(this.editModel != 0 && this.init)
            if (arguments[0]?.toString() == arguments[1]?.toString()) {
                console.log('return')
                return
            }
            if (this.editModel != 0 && this.init) {
                this.$set(this.form, 'unionChairmanId', '')
                
                this.$set(this.form, 'unionEmployees', [])
                this.$set(this.form, 'unionOrgName', '')
                this.$refs.table.refresh(true)
                this.addLine()
            }
        },
        isAudit: {
            immediate: true,
            handler(val) {
                if (val) {
                    this.$nextTick(() => {
                        this.editModel = '0'
                        this.addpersion = true
                        this.isAuth = 0
                    })
                }
            },
        },
    },
   async mounted() {
        this.$route.meta.title = ['组织架构查看', '组织架构编辑', '组织架构新增'][this.editModel]
        console.log(this.addpersion)
        if (this.editModel == 2) {
            this.addLine()
        }
        // 不为添加时请求详情
        if (this.editModel != 2) {
            this.loading.DRAFT = true
            this.loading.REJECTED = true
            this.loading.SUBMITTED = true
            getOrganization(this.id)
                .then((res) => {
                    this.loading.DRAFT = false
                    this.loading.REJECTED = false
                    this.loading.SUBMITTED = false
                    // this.form = this.$clone(res.data)
                    this.form = { ...res.data }

                    this.$nextTick(() => {
                        this.form.parentId = res.data.parentId
                        this.form.orgIds = res.data.orgIds
                        this.form.unionChairmanId = res.data.unionChairmanId
                        this.$nextTick(() => {
                            this.init = true
                        })
                    })
                    this.$refs.table.refresh(true)
                    this.form.unionEmployees.forEach((i) => {
                        i.key = this.key
                        i.isSave = true
                        i.editable = false
                        this.key++
                    })
                })

                .catch(() => {
                    this.loading.DRAFT = false
                    this.loading.REJECTED = false
                    this.loading.SUBMITTED = false
                })
        } else {
            this.$nextTick(() => {
                this.init = true
            })
        }
         //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('union_org_audit') 
    },

    computed: {
        formList() {
            return [
                {
                    keyName: 'unionLevelId',
                    disabled: this.editModel == 0,
                    label: '所属层级',
                    type: Selector,
                    attrs: {
                        urlType: 'union',
                        selectType: '1',
                        apiSuffix: 'queryTypesLabelListByAuth',
                    },
                },
                {
                    type: SelectUnionOrg,
                    keyName: 'parentId',
                    label: '上级工会组织',
                    disabled: this.editModel == 0,
                    attrs: {
                        form: this.form,
                        isAuth: this.isAuth,
                        isClear: this.editModel != '0',
                        isEdit: this.editModel == '1' || this.editModel == '0',
                    },
                },
                {
                    keyName: 'auditStatus',
                    hidden: this.editModel != 0,
                    slot: true,
                    hidden: !this.isAudit,
                    label: '状态',
                },
                {
                    type: SelectUnit,
                    keyName: 'orgIds',
                    disabled: this.editModel == 0,
                    attrs: {
                        orgIds: this.orgIds,
                        ref: 'selectUnit',
                        form: this.form,
                        isClear: this.editModel != '0',
                        isEdit: this.editModel == '1' || this.editModel == '0',
                    },
                    span: 24,
                    label: '单位',
                },
                {
                    keyName: 'unionOrgName',
                    type: 'BaseInput',
                    disabled: this.editModel == 0,
                    label: '组织简称',
                },

                {
                    keyName: 'unionEstDate',
                    type: 'a-date-picker',
                    placeholder: '请选择日期',
                    disabled: this.editModel == 0,
                    label: '成立时间',
                    attrs: {
                        valueFormat: 'YYYY-MM-DD',
                    },
                },
                {
                    keyName: 'unionVipNum',

                    slot: true,
                    label: '会员人数',
                },

                // {
                //     type: SelectOrgPeople,
                //     keyName: 'unionChairmanId',
                //     placeholder: '请选择工会主席',
                //     label: '工会主席',
                //     disabled: this.editModel == 0,

                //     attrs: {
                //         orgIds: this.form.orgIds,
                //         isArray: true,

                //         api: getUserDeptByOrgId,
                //         customRender: this.customRender,
                //     },
                // },
                // {
                //     keyName: 'unionChairmainJoinDate',
                //     type: 'a-date-picker',
                //     placeholder: '请选择日期',
                //     disabled: this.editModel == 0,
                //     label: '任职时间',
                //     attrs: {
                //         valueFormat: 'YYYY-MM-DD',
                //     },
                // },
                {
                    keyName: 'remarks',
                    type: 'BaseTextarea',
                    span: 24,
                    disabled: this.editModel == 0,
                    label: '备注',
                },
            ]
        },
    },
    methods: {
        isDisabled() {
            let flag = false
            if (this.editModel == 0) {
                flag = true
                if (this.addpersion == 'true') {
                    flag = false
                }
            }
            return flag
        },
        addLine() {
            this.form.unionEmployees.push({
                key: this.key,
                joinDate: '',
                phone: '',
                postId: '',
                userId: '',
                isSave: false,
                editable: true,
            })
            this.key++
            this.cacheData = this.form.unionEmployees.map((item) => ({ ...item }))
            this.$refs.table.refresh(true)
        },
        cancel(key, index) {
            const newData = [...this.form.unionEmployees]
            const target = newData.filter((item) => key === item.key)[0]
            this.editingKey = ''
            if (target.isSave) {
                if (target) {
                    Object.assign(target, this.cacheData.filter((item) => key === item.key)[0])
                    delete target.editable
                    this.form.unionEmployees = newData
                }
            } else {
                this.form.unionEmployees.splice(index, 1)
            }

            this.$refs.table.refresh(true)
        },
        save(data) {
            console.log(data)
            data.isSave = true
            data.editable = false
            this.editingKey = ''
            this.$refs.table.refresh(true)
        },
        edit(key) {
            console.log(key)
            const newData = [...this.form.unionEmployees]
            const target = newData.filter((item) => key === item.key)[0]
            this.editingKey = key
            if (target) {
                target.editable = true
                this.form.unionEmployees = newData
            }
            this.cacheData = this.form.unionEmployees.map((item) => ({ ...item }))
            this.$refs.table.refresh(true)
        },
        del(data, idx) {
            this.form.unionEmployees.splice(idx, 1)
            this.$refs.table.refresh(true)
        },
        validateTable() {
            let flag = false

            this.form.unionEmployees.forEach((i) => {
                i.editable = false
                this.editingKey = ''
                if (!i.postId || !i.userId || !i.joinDate) {
                    flag = true
                }
            })

            this.$refs.table.refresh(true)
            return flag
        },
        /**
         * 提交表单
         */
        handleSubmit(auditStatus) {
            let that = this
            that.setProcessConfig = null; 
            let api = [updateOrganization, addOrganization][that.editModel - 1] // 根据操作切换url地址
            console.log(this.form)
            this.form.unionEmployees.filter((item) => {})
            that.$refs.ruleForm.validate((e) => {
                if (e) {
                    // 提交表单
                    if (this.form.unionEmployees.length == 0) {
                        that.$message.warning('请添加管理人员数据')
                        return
                    }
                    if (that.validateTable()) {
                        that.$message.warning('请完善管理人员表格！')
                        return
                    }
                    if (this.addpersion == 'true') {
                        api = updateOrganization
                        this.editParsion = true
                    }
                    that.loading[auditStatus] = true
                    that.form.auditStatus = auditStatus
                    that.form.orgIds = typeof that.form.orgIds == 'string' ? [that.form.orgIds] : this.form.orgIds

                    this.submitApprovalConfirm(auditStatus == 'SUBMITTED'?this.processConfig:6,(flag)=>{
                      if(!flag) {
                          that.loading[auditStatus] = false
                          return
                        }
                       api(that.form)
                        .then((res) => {
                            that.loading[auditStatus] = false
                            that.editParsion = false

                            if (auditStatus === 'DRAFT') {
                                that.$message.success('保存成功！')
                                that.$multiTab.close()
                            }else if(auditStatus === 'SUBMITTED'){
                                that.businessId = res.data.id;
                                that.setProcessConfig = this.processConfig;
                                that.$message.success('提交成功！')
                            }
                             else {
                                  that.$message.success('提交成功！')
                                  that.$multiTab.close()
     
                            }
                        })
                        .catch((res) => {
                            that.$message.warning(res.data.msg)
                            that.editParsion = false
                            that.loading[auditStatus] = false
                        })
                      })
                }
            })

            // 校验表单
        },
        changeDepId(name, e) {
            console.log(e)
            if (this.editModel == 2) {
                if (e?.length == 1) {
                    this.$nextTick(() => {
                        this.form.unionOrgName =
                            this.$refs.customForm?.$refs.ruleForm?.$refs.selectUnit?.getValueName(e[0]) + '工会'
                    })
                } else {
                    this.form.unionOrgName = ''
                }
            }
        },
        changeOrg() {
            let e = arguments[1]
            this.orgIds = e?.orgIds || []
        },
        changePersonNumber(e) {
            console.log(e)
            this.form.unionVipNum = e
        },

        handleClose() {
            if (this.isAudit) {
                window.close()
            } else {
                this.$multiTab.close(this.$route.fullpath)
            }
        },
    },
}
</script>

<style lang="less" scoped>

.file_prompt {
    color: #999;
}
</style>